<template>
  <div class="accountadd">
    <div class="header">添加账号</div>
    <div class="main">
      <el-form
        ref="accountForm"
        :rules="rules"
        :model="accountForm"
        label-width="80px"
        size="mini"
      >
        <!-- 账号 -->
        <el-form-item prop="account" label="账号">
          <el-input v-model="accountForm.account"> </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input type="password" v-model="accountForm.password"></el-input>
        </el-form-item>
        <!-- 用户组 -->
        <el-form-item prop="userGroup" label="用户组">
          <el-select v-model="accountForm.userGroup" placeholder="请选择用户组">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <!-- 添加 -->
      <div class="btn">
        <el-button size="small" type="primary" @click="accountAddto"
          >添加
        </el-button>
        <!-- 重置 -->
        <el-button size="small" @click="accountReset">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// 引入工具函数
import { checkaccount, checkpassword } from '@/utils/utils';
// 引入配置好的axios函数
import { addAccount } from '../../api/user';
export default {
  data () {
    return {
      // 表单数据
      accountForm: {
        account: '',
        password: '',
        userGroup: '',
      },
      rules: {
        //验证用户名
        account: [
          { validator: checkaccount, trigger: 'blur' }
        ],
        //验证密码
        password: [
          { validator: checkpassword, trigger: 'blur' },
        ],
        //验证用户组
        userGroup: [{ required: true, message: '请输入账号', trigger: 'change' }],
      },
    }
  },
  methods: {
    //点击添加按钮进行验证
    accountAddto () {
      this.$refs.accountForm.validate(async (valid) => {
        if (valid) {
          console.log('this.accountForm :>> ', this.accountForm)
          //浅拷贝
          let res = await addAccount({ ...this.accountForm })
          // 解构对象
          let { code, msg } = res.data
          //判断请求状态
          if (code == 0) {

            //跳转到用户列表页面
            this.$router.push('/account')
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error'
          });
        }
      })
    },
    //点击重置按钮重置页面内容
    accountReset () {
      this.$refs.accountForm.resetFields()
    },
  },
}
</script>

<style lang="less" scoped>
.header {
  line-height: 50px;
  padding-left: 10px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
}
.main {
  margin-top: 20px;
  padding-left: 30px;
  padding-bottom: 30px;
  width: 300px;
  .btn {
    width: 300px;
    display: flex;
    justify-content: center;
  }
}
</style>